<template>
  <!-- 设备配置 -->
  <div class="supplier table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.supplierName" placeholder="模糊搜索供应商名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="keywords">
        <el-input v-model="queryParams.supplierRepo" placeholder="模糊搜索供应商负责人" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" @click="handleQuery" type="primary">搜索</el-button>
        <el-button size="mini" @click="handleAdd" type="primary">新增</el-button>
        <el-button size="mini" @click="handleImport" type="primary">批量导入</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table v-loading="loading" size="mini" :data="operationList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="45" align="center" />-->
      <el-table-column type="index" label="序号" width="60" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="supplierId" label="供应商ID" width="80" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="supplierName" label="供应商名称" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="supplierRepo" label="供应商负责人" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="supplierPhone" label="供应商联系方式" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="supplierRoughlyAddress" min-width="160" :formatter="methodFormat" show-overflow-tooltip label="供应商地址" align="center"></el-table-column>
      <el-table-column prop="supplierUrl" min-width="140" label="供应商网址" align="center" show-overflow-tooltip></el-table-column>
      <!-- <el-table-column prop="supplierSend" label="供应商推送"></el-table-column> -->
      <el-table-column label="使用状态" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isValid" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="operation" label="操作" width="140" align="center" class-name="small-padding fixed-width" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button size="mini" class="btn" v-hasPermi="['system:role:edit']" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.supplierId)" v-hasPermi="['slope:supplier:remove']">删除</el-button>
          <!--<template>-->
            <!-- <el-button v-if="scope.row.isValid" size="mini" class="btn" @click="handleEnable(scope.row)">启用</el-button>
            <el-button v-else size="mini" class="btn" @click="handleDisable(scope.row)">禁用</el-button> -->
          <!--</template>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <Add ref="add" @refresh="getList"></Add>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的供应商数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listSupplier, importTemplate,enableSupplier,disableSupplier, deleteSupplier } from "@/api/slope/supplier";
  import { getToken } from "@/utils/auth";
  import Add from "./add";
  export default {
    name: "supplier",
    components: {
      Add
    },
    data() {
      return {
        tableHeight: 400,
        // 角色表格数据
        operationList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          supplierName: '',
          supplierRepo: '',
        },
        // 日期条件
        dateRange: [],
        // 表单参数
        form: {
          name: "",
          sensorType: "",
          number: "",
          imei: "",
          pointName: "",
          site: {
            address: "",
            lon: "",
            lat: ""
          },
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        rules: {},
        /** 地图相关 */
        olMap: null,
        coordinate: [],
        layerConfig: {
          Amap: {
            title: "高德",
            server: "https://webst01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&style=6"
          }
        },
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/slope/supplier/importDevice"
        },
        // 导出加载框
        exportLoading: {
          lock: true,
          text: '正在导出文件，请稍等',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /**
       * 删除供应商管理
       * @param id 供应商管理id
       */
      deleteInfo(id) {
        let self = this;
        self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            deleteSupplier(id).then((res)=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            }).catch(()=>{
              self.getList();
            });
          })
          .catch(function() {
        });
      },
      /** 查询角色列表 */
      getList() {
        let self = this;
        self.loading = true;
        listSupplier(self.addDateRange(self.queryParams, self.dateRange)).then(response => {
          self.operationList = response.rows;
          self.total = response.total;
          self.loading = false;
        }).catch((error)=> {
          self.loading = false;
          console.log(error);
        });
      },

      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      methodFormat(row, column) {
        let needRoughlyAddress = "";
        try {
          let needResult = row.supplierRoughlyAddress.split(" ");
          for (let i = 0; i <= 2;i++){
            needRoughlyAddress += needResult[i]+" ";
          }
        } catch {

        }
        return needRoughlyAddress ;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.$refs.add.handleClick({
          title: "添加供应商",
          submit: this.handleSubmit
        });
      },
      /** 编辑按钮操作 */
      handleEdit(row) {
        this.$refs.add.handleClick({
          info: row,
          title: "编辑供应商",
          submit: this.handleSubmit
        });
      },

      handleStatusChange(row){
        console.log(row);
        if(row.isValid=="1"){
          this.handleDisable(row);
        }else{
          this.handleEnable(row);
        }
      },

      /** 编辑按钮操作 */
      handleEnable(row) {
        let self = this;
        self.$confirm( '确认要启用供应商"'+row.supplierName+'"吗', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(function() {
            let data = row.supplierId;
            return enableSupplier(data);
          })
          .then(() => {
            self.msgSuccess("启用成功");
          })
          .catch(function() {
            if(row.isValid=="0"){
              row.isValid="1";
            }else{
              row.isValid="0";
            }
          });
      },

      /** 编辑按钮操作 */
      handleDisable(row) {
        let self = this;
        self.$confirm( '确认要禁用供应商"'+row.supplierName+'"吗', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(function() {
            let data = row.supplierId;
            return disableSupplier(data);
          })
          .then(() => {
            self.msgSuccess("禁用成功");
          })
          .catch(function() {
            if(row.isValid=="0"){
              row.isValid="1";
            }else{
              row.isValid="0";
            }
          });
      },

      /** 提交操作 */
      handleSubmit(info) {
        console.log(info, 11);
        return Promise.resolve(true);
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "供应商导入";
        this.upload.open = true;
      },
      /** 导出按钮操作 */
      handleExport() {
        //todo
      },
      /** 下载模板操作 */
      importTemplate() {
        let self = this;
        let loading = self.$loading(self.exportLoading);
        importTemplate().then(response => {
          this.download(response.msg);
          loading.close();
        }).catch((error)=> {
          loading.close();
          console.log(error);
        });
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
  };
</script>

<style lang="scss" scoped>
  .supplier {
    .upload-demo {
      display: inline-block;
      margin-left: 10px;
    }
  }
</style>
